package com.laundry.service;

import com.laundry.entity.User;
import com.laundry.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    
    private final UserRepository userRepository;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 优先按用户名查找
        User user = userRepository.findByUsername(username).orElse(null);

        // 如果按用户名找不到，再按邮箱查找
        if (user == null) {
            user = userRepository.findByEmail(username).orElse(null);
        }

        // 如果按邮箱找不到，再按手机号查找
        if (user == null) {
            user = userRepository.findByMobile(username).orElse(null);
        }

        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        return user;
    }
}
